package com.example.demo.redis;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class RedisImpl implements RedisUtil {

    StringRedisTemplate stringRedisTemplate;

    @Autowired
    public RedisImpl(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public void strSet(String key, String val) {
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        ops.set(key, val);
    }

    @Override
    public String strGet(String key){
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        return ops.get(key);
    }

    @Override
    public String strGetSet(String key, String val) {
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        return ops.getAndSet(key, val);
    }

    @Override
    public void strSetEx(String key, String val, Long exTime) {
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        ops.set(key, val, exTime, TimeUnit.SECONDS);
    }

    @Override
    public List<String> strGet(List<String> stringList) {
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        return ops.multiGet(stringList);
    }

    @Override
    public void strSet(Map<String, String> map) {
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        ops.multiSet(map);
    }


    @Override
    public Long strGetExpire(String key) {
        return stringRedisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    @Override
    public void strDel(String key) {
        stringRedisTemplate.delete(key);
    }

    @Override
    public Boolean strHasKey(String key) {
        return stringRedisTemplate.hasKey(key);
    }

    @Override
    public void strSetExpire(String key, Long expTime) {
        stringRedisTemplate.expire(key, expTime, TimeUnit.SECONDS);
    }

    @Override
    public void strDel(List<String> keys) {
        stringRedisTemplate.delete(keys);
    }

    @Override
    public void strSetExpireAt(String key, Date date) {
        stringRedisTemplate.expireAt(key, date);
    }

    @Override
    public Boolean strSetIfAbsent(String key, String val) {
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        return ops.setIfAbsent(key, val);
    }

    @Override
    public Set<String> strKeyS(String key) {
        return stringRedisTemplate.keys("*" + key + "*");
    }
}
